package com.itheima.canal.listener;


//需求：该监听类，通过canal，监听spu表，
// 并把上下架状态改变的商品ID，发送到自己定义的交换机和队列中

import com.alibaba.otter.canal.protocol.CanalEntry;
import com.itheima.canal.config.RabbitMQConfig;
import com.xpand.starter.canal.annotation.CanalEventListener;
import com.xpand.starter.canal.annotation.ListenPoint;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CanalEventListener
public class SpuListener {

	@Autowired
	RabbitTemplate rabbitTemplate;

	//定义监听方法，监听商品下架
	@ListenPoint(schema = "changgou_goods", table = "tb_spu") //不要漏掉该句
	public void goodUpListener(CanalEntry.EntryType entryType, CanalEntry.RowData rowData) {
		//获取修改之前的商品map
		Map oldMap = new HashMap<>();
		rowData.getBeforeColumnsList().forEach((c) -> oldMap.put(c.getName(), c.getValue()));

		//获取修改之后的商品map
		Map newMap = new HashMap();
		rowData.getAfterColumnsList().forEach((c) -> newMap.put(c.getName(), c.getValue()));

		//判断前后的上下架状态是否是 0到1
		if ("0".equals(oldMap.get("is_marketable")) && "1".equals(newMap.get("is_marketable"))) {
			//若是，则发送到交换机 和 队列
			rabbitTemplate.convertAndSend(RabbitMQConfig.GOODS_UP_EXCHANGE, RabbitMQConfig.SEARCH_ADD_QUEUE, newMap.get("id"));
		}
	}

	//定义监听方法，监听商品下架
	@ListenPoint(schema = "changgou_goods", table = "tb_spu")
	public void goodDownListener(CanalEntry.EntryType entryType, CanalEntry.RowData rowData) {
		//判断该商品是否下架
		List<CanalEntry.Column> oldList = rowData.getBeforeColumnsList();
		List<CanalEntry.Column> newList = rowData.getAfterColumnsList();


		Map oldMap = new HashMap();
		Map newMap = new HashMap();


		for (CanalEntry.Column column : oldList) {
			oldMap.put(column.getName(), column.getValue());
		}
		for (CanalEntry.Column column : newList) {
			newMap.put(column.getName(), column.getValue());
		}


		if ("1".equals(oldMap.get("is_marketable")) && "0".equals(newMap.get("is_marketable"))) {
			//发送spu的id，到下架交换机
			rabbitTemplate.convertAndSend(RabbitMQConfig.GOODS_DOWN_EXCHANGE, "", newMap.get("id"));
		}

	}
}

